#include "ExampleLayer.hpp"
#include <imgui.h>

#include "../Core/Application.hpp"
#include "../ImGuiLayer/UIWindows/GameView.h"
#include "../Primitive/GeometryGenerator.h"
#include "../Primitive/PrimitiveGenerator.h"
#include <imgui_internal.h>

ExampleLayer::ExampleLayer() : Layer("ExampleLayer")
{
	lastMousePosition = glm::vec2(0, 0);
	bFirstMouse = false;
}

int id = -1;
void ExampleLayer::OnAttach()
{
	Kriko::RenderCommand::SetCamera(Kriko::Application::Get().GetCameraPtr());

	object = new Kriko::RenderObject();

	// set shader
	std::shared_ptr<Shader> cubeShader = std::make_shared<Shader>("Shader/Plane.vert.glsl", "Shader/Plane.frag.glsl");
	// set mesh
	auto cubeMesh = std::make_shared<GeometryGenerator::MeshData>(GeometryGenerator::CreateSphere(1, 100, 100));
	// set transform
	std::shared_ptr<Kriko::Transform> cubeTransform = std::make_shared<Kriko::Transform>();
	// set texture
	std::shared_ptr<Kriko::Texture> texture = std::make_shared<Kriko::Texture>();
	texture->m_data = stbi_load("Resources/container.jpg", &texture->m_width, &texture->m_height, &texture->m_channels, 0);
	object->SetMesh(cubeMesh);
	object->SetShader(cubeShader);
	object->SetTransform(cubeTransform);
	object->SetTexture(texture);
	
	Kriko::RenderCommand::SetRenderObject(object);

	Kriko::RenderCommand::SetFrameBufferSize(Kriko::Application::Get().GetWindow().VGetWidth(), Kriko::Application::Get().GetWindow().VGetHeight());
	gameView = new Kriko_View::GameView("GameView", &id);

	gameController = new Kriko::GameController(Kriko::Application::Get().GetCameraPtr());
	gameController->SetControlStatePtr(gameView->GetWndFocusPtr());
}

void ExampleLayer::OnDetach()
{
	
}
float rotateSpeed = 1.0f;
void ExampleLayer::OnUpdate(const Kriko::TimeStep& p_deltaTime)
{
	gameController->Update(p_deltaTime);
	
	auto transform = object->GetTransformPtr();
	transform->RotateBy(rotateSpeed * p_deltaTime.GetSecond(), glm::vec3(0, 1, 0));

	Kriko::RenderCommand::SetClearColor(Kriko::RenderCommand::GetClearColor());
	Kriko::RenderCommand::Clear();
	id = Kriko::RenderCommand::FrameBufferRender();
}
void ExampleLayer::OnImGuiRender()
{
	gameView->Render();
	ImGui::Begin("Protertory");
	ImGui::End();
}

void ExampleLayer::OnEvent(IEventDataPtr pEvent)
{
	gameController->OnKeyEvent(pEvent);
	gameController->OnMouseButton(pEvent);
	gameController->OnMouseMove(pEvent);
}
